package com.zds.support.base

import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Looper
import android.widget.Toast
import androidx.multidex.MultiDexApplication
import com.zds.support.R
import com.zds.support.manager.UserDataManager
import com.zds.support.util.AppUtils

import java.lang.ref.WeakReference
import java.util.*

/**
 *
 *@Description
 *@Author zc
 *@Version V1.0
 **/
abstract class SupportBaseApplication : MultiDexApplication() {
    val wrActivities = ArrayList<WeakReference<Activity>>()
    var isRunInBackground = false

    companion object {
        var supportBaseApplication: SupportBaseApplication? = null
    }

    override fun onCreate() {
        super.onCreate()
        supportBaseApplication = this
        AppUtils.appContext = this

        if (AppUtils.isMainProcess(this)) {
            initConfig()
        }
        initAppBackgroundCallBack()
    }

    open fun initConfig() {

    }

    open fun logout(code: String?, msg: String?) {
        UserDataManager.instance.logout()
    }

    fun restartApp(isError: Boolean = false) {
        val context = this
        if (isError) {
            Thread(Runnable {
                Looper.prepare()
                Toast.makeText(context, R.string.sorry_app_uncaught_exception_error, Toast.LENGTH_LONG).show()
                Looper.loop()

            }).start()
            try {
                Thread.sleep(1000);
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }


        try {
            val application = context.applicationContext
            val intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName())
            intent?.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val restartIntent = PendingIntent.getActivity(
                    context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
            //退出程序
            val mgr = application.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            mgr.set(
                    AlarmManager.RTC, System.currentTimeMillis() + 50,
                    restartIntent) // 1秒钟后重启应用
            if (application is SupportBaseApplication) {
                application.exit()
            }
            //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
            android.os.Process.killProcess(android.os.Process.myPid())
        } catch (e: Exception) {

        }
    }

    fun exit() {

    }

    fun updateLanguage(locale: Locale) {

    }
    fun onActivityCreated(wrActivity: WeakReference<Activity>) {
        wrActivities.add(wrActivity)
    }


    fun onActivityDestroyed(wrActivity: WeakReference<Activity>) {
        wrActivities.remove(wrActivity)
    }
    fun initAppBackgroundCallBack() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            private var activityStartedCount = 0
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            }

            override fun onActivityStarted(activity: Activity) {
                activityStartedCount++
                if (isRunInBackground) {
                    isRunInBackground = false
//                    backToApp(activity)
                }
            }

            override fun onActivityResumed(activity: Activity) {
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
                activityStartedCount--
                if (activityStartedCount == 0) {
                    isRunInBackground = true
//                    leaveApp(activity)
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
            }


        })
    }
}